""" 命令行交互方法模块

为命令行交互，提供接口

用于组织统计手段与被统计对象的交互的类： Launch
"""
import argparse
import logging
import os.path

from code_metric.codes import Repo, File, Version, Organization, Contribution, Commit, DefaultVIHandler
from code_metric.config import init_global_config_setting
from code_metric.handler import OHVersionInfoHandler, OHReportInfoHandler
from code_metric.metric import GitBlame, Cloc, Stats, GitShow, DefaultRIHandler
from code_metric.utils import is_repo_valid, is_organization_valid, is_token_valid, clock

CONFIG = init_global_config_setting()
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

assert is_token_valid(CONFIG['access_token']), '请于config.toml, 配置有效的access_token'

if CONFIG['environment'] == 'dev':
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
    # logging.disable(logging.DEBUG)
else:
    logging.basicConfig(filename=BASE_DIR + '/stats.log',
                        level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')


@clock
def launch_stats_for_commit(args):
    launch = Launch(args.org)
    for commit in args.sha:
        launch.blame_report_for_commit(args.repo, commit)


@clock
def launch_stats_for_org(args):
    launch = Launch(args.org)
    if args.cloc:
        no_third = False if args.filter is None else args.filter
        launch.cloc_report_for_version(no_third=no_third)
    elif args.blame:
        no_third = True if args.filter is None else args.filter
        launch.blame_report_for_version(no_third=no_third)


@clock
def launch_stats_for_version(args):
    launch = Launch(args.org)
    for version in args.ver:
        if args.cloc:
            no_third = False if args.filter is None else args.filter
            launch.cloc_report_for_version(version_name=version, no_third=no_third)
        elif args.blame:
            no_third = True if args.filter is None else args.filter
            launch.blame_report_for_version(version_name=version, no_third=no_third)
        elif args.group:
            launch.group_report_for_version(version_name=version)
        else:
            print('请通过 python stats.py version -h 查看使用帮助；需要传入统计维度参数')
            break


@clock
def launch_stats_for_repo(args):
    launch = Launch(args.org)
    for repo in args.repo:
        if args.cloc:
            launch.cloc_report_for_repo(repo, ref_name=args.ref, ref_type=args.type)
        elif args.blame:
            launch.blame_report_for_repo(repo, ref_name=args.ref, ref_type=args.type)
        else:
            print('请通过 python stats.py repo -h 查看使用帮助；需要传入统计维度参数')
            break


@clock
def launch_stats_for_file(args):
    launch = Launch(args.org)
    for file in args.path:
        launch.blame_report_for_file(args.repo, file, ref_name=args.ref, ref_type=args.type)


class Launch:
    def __init__(self, owner_name):
        assert is_organization_valid(owner_name), '请传入有效的组织名，例如：openharmony'
        self.owner_name = owner_name
        self.stat_handler = _get_stat_handler_of_organization(owner_name)
        self.info_handler = _get_info_handler_of_organization(owner_name)

    def blame_report_for_commit(self, repo_name, commit_sha):
        assert is_repo_valid(self.owner_name, repo_name), '请传入有效的属主仓库名，例如：(openharmony, docs)'
        Repo(self.owner_name, repo_name).init_repo_data()
        repo = Repo(self.owner_name, repo_name, ref=commit_sha, ref_type='SHA')
        repo.init_repo_data()
        commit = Commit(repo, commit_sha)

        stats = Stats.stat_commit(commit, stat_handler=self.stat_handler())
        print('报告位置:' + stats.get_commit_contribution_line_report())

    def blame_report_for_file(self, repo_name, file_name, ref_name='master', ref_type='Branch'):
        assert is_repo_valid(self.owner_name, repo_name), '请传入有效的属主仓库名，例如：(openharmony, docs)'
        repo = Repo(self.owner_name, repo_name, ref=ref_name, ref_type=ref_type)
        repo.init_repo_data()
        file = File(repo, file_name)
        assert os.path.isfile(file.path), f'文件{file.path}本体不存在'

        stats = Stats.stat_file(file, stat_handler=self.stat_handler())
        print('报告位置:' + stats.get_file_author_line_report())

    def cloc_report_for_repo(self, repo_name, ref_name='master', ref_type='Branch'):
        assert is_repo_valid(self.owner_name, repo_name), '请传入有效的属主仓库名，例如：(openharmony, docs)'
        repo = Repo(self.owner_name, repo_name, ref=ref_name, ref_type=ref_type)
        repo.init_repo_data()

        stats = Stats.stat_repo(repo, stat_handler=self.stat_handler())
        print('报告位置:' + stats.get_repo_code_line_report())

    def blame_report_for_repo(self, repo_name, ref_name='master', ref_type='Branch'):
        assert is_repo_valid(self.owner_name, repo_name), '请传入有效的属主仓库名，例如：(openharmony, docs)'
        repo = Repo(self.owner_name, repo_name, ref=ref_name, ref_type=ref_type)
        repo.init_repo_data()

        stats = Stats.stat_repo(repo, stat_handler=self.stat_handler())
        print('报告位置:' + stats.get_repo_author_line_report())

    def cloc_report_for_version(self, version_name='master', no_third=False):
        version = Version(self.owner_name, version_name,
                          info_handler=self.info_handler(version_name=version_name, owner_name=self.owner_name))
        version.init_version_repos_data()

        stats = Stats.stat_version(version, stat_handler=self.stat_handler(no_third=no_third))
        print('报告位置:' + stats.get_version_repos_code_line_report())

    def blame_report_for_version(self, version_name='master', no_third=True):
        version = Version(self.owner_name, version_name,
                          info_handler=self.info_handler(version_name=version_name, owner_name=self.owner_name))
        version.init_version_repos_data()

        stats = Stats.stat_version(version, stat_handler=self.stat_handler(no_third=no_third))
        print('报告位置:' + stats.get_version_repos_author_line_report())

    def group_report_for_version(self, version_name='master'):
        version = Version(self.owner_name, version_name,
                          info_handler=self.info_handler(version_name=version_name, owner_name=self.owner_name))
        version.init_version_repos_data()

        stats = Stats.stat_version(version, stat_handler=self.stat_handler())
        stats.get_version_repos_code_line_report()

        stats = Stats.stat_version(version, stat_handler=self.stat_handler(no_third=True))
        stats.get_version_repos_author_line_report()
        print('报告位置:' + stats.get_version_repos_group_line_report())


def _get_info_handler_of_organization(org_name):
    if org_name == 'openharmony':
        return OHVersionInfoHandler
    else:
        return DefaultVIHandler


def _get_stat_handler_of_organization(org_name):
    if org_name == 'openharmony':
        return OHReportInfoHandler
    else:
        return DefaultRIHandler


if __name__ == '__main__':
    pass
    test = Launch('openharmony')
    test.blame_report_for_commit('vendor_lockzhiner', 'bdddde9866d0d3e6efb37337c19c231ea3e142b5')

    file_to_test = 'ability_ability_base\\test\\unittest\\want\\want_test.cpp'
    test.blame_report_for_file('ability_ability_base', file_to_test,
                               ref_name='OpenHarmony-v3.2-Release', ref_type='Tag')

    test.cloc_report_for_repo('graphic_surface', ref_name='OpenHarmony-1.0', ref_type='Tag')
    test.blame_report_for_repo('graphic_surface', ref_name='OpenHarmony-1.0', ref_type='Tag')

    test.cloc_report_for_version(version_name='OpenHarmony-3.2-Release', no_third=False)
    test.blame_report_for_version(version_name='OpenHarmony-3.2-Release', no_third=True)
    test.group_report_for_version(version_name='OpenHarmony-3.2-Release')
